@echo off
ECHO Computing CRC(VCU version)
ECHO -------------------------------------

set TOOL_PATH=%~dp0
set TARGET_NAME=%1
set TARGET_PATH=%2
set PROJECT_PATH=%3
set OUTPUT_NAME=%4


SET SREC_PATH=%TOOL_PATH%crc_tool
SET MAP_FILE=%TARGET_PATH%%TARGET_NAME%.map
SET INPUT_HEX_OLD=%TARGET_PATH%%TARGET_NAME%.hex
SET INPUT_HEX=%TARGET_PATH%%TARGET_NAME%_BUF.hex
SET OUTPUT_HEX=%PROJECT_PATH%..\bin\%OUTPUT_NAME%.hex
SET TMP_FILE=tmp_file.txt

::-----------------get CRC address information line
ECHO Extracting CRC address from MAP file
FINDSTR /R /C:"^  *CHECKSUM" %MAP_FILE%>%TMP_FILE%
SET /p crc_search=<%TMP_FILE%
DEL %TMP_FILE%
::-----------------CRC address
for /f "tokens=1 delims=(" %%a in ("%crc_search%") do set crc_search=%%a
SET crc_search=%crc_search:CHECKSUM=%
for /f "tokens=1 delims= " %%a in ("%crc_search%") do set CRC_ADDR=%%a

ECHO Extracting APP_START_ADDR address from MAP file
FINDSTR /R /C:"^  *__Vectors " %MAP_FILE%>%TMP_FILE%
SET /p app_start_search=<%TMP_FILE%
@REM ECHO app_start_search=%app_start_search%
DEL %TMP_FILE%
for /f "tokens=1 delims=(" %%a in ("%app_start_search%") do set app_start_search=%%a
REM remove CHECKSUM string from variable
SET app_start_search=%app_start_search:__Vectors=%
REM get first word at line, which should be CRC address in HEX format
for /f "tokens=1 delims= " %%a in ("%app_start_search%") do set APP_START_ADDR=%%a

ECHO -------------------------------------
ECHO CRC address: %CRC_ADDR%
ECHO APP start address: %APP_START_ADDR%
ECHO -------------------------------------


SET /a CRC_ADDR_END=%CRC_ADDR%+4
::-----------------choose CRC32 or CRC16
FINDSTR /R /C:"^  *crc_block_data_calculate" %MAP_FILE% > nul && call :OK||call :NO

goto :eof
:OK
ECHO --------------------CRC32
%SREC_PATH%\srec_cat.exe %INPUT_HEX_OLD% -intel -crop %APP_START_ADDR% %CRC_ADDR%  -fill 0xff %APP_START_ADDR% %CRC_ADDR%  -stm32-l-e %CRC_ADDR%  -o  %OUTPUT_HEX% -intel
::bin\srec_cat.exe Output\Raptor_VCU.hex -intel -crop %APP_START_ADDR% %CRC_ADDR%   -stm32-l-e %CRC_ADDR%  -o  Output\Raptor_VCU_checked.hex -intel
%SREC_PATH%\srec_cat.exe %INPUT_HEX_OLD% -intel  -crop %APP_START_ADDR% %CRC_ADDR% %OUTPUT_HEX% -intel  -crop %CRC_ADDR% %CRC_ADDR_END%  -o %INPUT_HEX_OLD% -intel
ECHO -------------------------------------   
goto :eof

:NO
ECHO --------------------CRC16
%SREC_PATH%\srec_cat.exe %INPUT_HEX_OLD% -intel -crop %APP_START_ADDR% %CRC_ADDR%  -fill 0xff %APP_START_ADDR% %CRC_ADDR%  -crc16-l-e %CRC_ADDR% -POLYnomial ccitt -XMODEM  -o  %OUTPUT_HEX% -intel
%SREC_PATH%\srec_cat.exe %INPUT_HEX_OLD% -intel  -crop %APP_START_ADDR% %CRC_ADDR% %OUTPUT_HEX% -intel  -crop %CRC_ADDR% %CRC_ADDR_END%  -o %INPUT_HEX_OLD% -intel
ECHO -------------------------------------   
goto :eof

exit